<template>
  <div class="editName">
    <van-popup :value="userName" position="right" @open="handleOpen">
      <van-nav-bar
        title="修改昵称"
        left-text=""
        right-text="保存"
        left-arrow
        @click-left="handleBack"
        @click-right="onClickRight"
      />
      <van-form ref="form">
        <van-field
          v-model.trim="userInfoNickNames"
          placeholder="请输入用户名"
          :rules="rules"
        />
      </van-form>
    </van-popup>
  </div>
</template>

<script>
import { auEdit } from '@/api/my.js'
export default {
  name: 'EditName',
  props: {
    userName: {
      type: Boolean,
      default: false
    },
    userInfoNickName: {
      type: String,
      default: ''
    }
  },
  model: {
    prop: 'userName'
  },
  data () {
    return {
      value: '',
      userInfoNickNames: '', // 用于双向绑定
      beforeEditNickName: '', //  用于验证的对比
      rules: [
        {
          required: true,
          message: '必填',
          trigger: 'onBlur'
        },
        {
          validator: (newNickName) => {
            return newNickName.length > 1 && newNickName.length < 7
          },
          message: '长度为2至6位数',
          trigger: 'onChange'
        },
        {
          validator: (newNickName) => {
            return newNickName !== this.beforeEditNickName
          },
          message: '您未做修改',
          trigger: 'onChange'
        }
      ]
    }
  },
  methods: {
    // 打开弹窗时,把父组件传过来的值设置给对应参数
    handleOpen () {
      this.userInfoNickNames = this.userInfoNickName
      this.beforeEditNickName = this.userInfoNickName
    },
    // 点击返回按钮
    handleBack () {
      this.$emit('refreshPage')
      this.$emit('input', false)
    },
    onClickRight () {
      this.$refs.form
        .validate()
        .then(() => {
          const afterEditNickName = this.userInfoNickNames
          auEdit({ nickname: afterEditNickName })
          this.$toast.success('修改成功')
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="less" scoped>
.van-popup {
  width: 100%;
  height: 100%;
}
::v-deep .van-field__control {
  margin-top: 20px;
  height: 80px;
  background-color: #f7f4f5;
}
</style>
